package com.wn.common.utils

import android.content.res.AssetManager
import com.blankj.utilcode.util.GsonUtils
import com.google.gson.reflect.TypeToken
import com.wn.common.db.entity.VideoInfo
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.coroutines.resumeWithException

/**
 * @Author: wn
 * @Date: 2024/11/6 17:04
 * @Description: 解析本地 assets目录下 JSON文件 转为 实体类
 * 以异步的方式读取 assets目录下的文件，并且适配协程的写法，让他真正挂起函数
 * 直接以同步的方法拿到返回值
 */
object ParseFileUtils {
  /**
   * 解析本地 assets目录下 JSON文件 转为 实体类列表
   * @param assetManager AssetManager
   * @param fileName String
   * @return MutableList<VideoInfo>
   */
  suspend fun parseAssetsFile(
    assetManager: AssetManager,
    fileName: String,
  ): MutableList<VideoInfo> = suspendCancellableCoroutine { continuation ->
    try {
      val inputStream = assetManager.open(fileName)
      // 逐行读取，不用逐个字节读取
      val bufferedReader = BufferedReader(InputStreamReader(inputStream))
      var line: String?
      val stringBuilder = StringBuilder()
/*
      kotlin中不允许这样写
      while ((line = bufferedReader.readLine()) != null) {

      }
*/

      do {
        line = bufferedReader.readLine()
        if (line != null) stringBuilder.append(line) else break
      } while (true)

      inputStream.close()
      bufferedReader.close()
//        val list = stringBuilder.toString().toBean<MutableList<VideoInfo>>()
      /**
       * 1 单一实体对象         GsonUtils.fromJson(str, Person::class.java.class)
       * 2 对象列表或者其他结构  GsonUtils.fromJson(str, object : TypeToken<MutableList<VideoInfo>>() {}.type)
       */
      val type = object : TypeToken<MutableList<VideoInfo>>() {}.type
      val list = GsonUtils.fromJson<MutableList<VideoInfo>>(stringBuilder.toString(), type)
      continuation.resumeWith(Result.success(list))
    } catch (e: Exception) {
      e.printStackTrace()
      continuation.resumeWithException(e)
    }
  }
}